package agents.behaviours;

import java.io.IOException;

import weka.core.Instances;

import agents.model.DataServiceAgent;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.FIPANames;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

public class DataServiceBehaviour extends CyclicBehaviour {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public DataServiceBehaviour(){
		super();
		
	}
	@Override
	public void onStart() {
		super.onStart();
		if(!(myAgent instanceof DataServiceAgent)){
			throw new RuntimeException("The DataServicesBehavior is only for agents derived from DataServiceAgent!");
		}
	}
	
	@Override
	public void action() {
		MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM_IF), MessageTemplate.MatchProtocol(FIPANames.InteractionProtocol.FIPA_QUERY));
		ACLMessage msg = myAgent.blockingReceive(mt);
		// 
		Instances instances = ((DataServiceAgent)myAgent).getData();
		if(instances.attribute(msg.getContent()) == null){
			throw new RuntimeException("Attribute " + msg.getContent() + " is not in data set!");
		}
		boolean contains = getDataStore().get(msg.getContent()) !=null;
		//update attribute
		ACLMessage reply = msg.createReply();
		if(!contains){
			getDataStore().put(msg.getContent(), true);
			reply.setPerformative(ACLMessage.INFORM);
			try {
				reply.setContentObject(instances);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}else{
			reply.setPerformative(ACLMessage.REFUSE);
		}
		myAgent.send(reply);

	}

	
	
}
